package com.lin.sys.service.impls;


import org.apache.dubbo.config.annotation.Service;
import com.lin.common.service.impl.BaseService;
import com.lin.sys.dao.SysMenuMapper;
import com.lin.sys.entity.SysMenu;


import dto.SysMenuDto;
import org.springframework.beans.factory.annotation.Autowired;
import service.MenuService;
import service.RoleMenuService;
import util.BeanUtils;
import util.ResponseVo;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl extends BaseService<SysMenu> implements MenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private UserIdWorker idWorker;
    @Override
    public List<SysMenuDto> findUserPermissions(Long userid) {
        List<SysMenu> userPermissions = sysMenuMapper.findUserPermissions(userid);
        return BeanUtils.copyList(userPermissions,SysMenuDto.class);
    }

    @Override
    public ResponseVo addMenu(SysMenuDto menu) {
        SysMenu sysMenu=new SysMenu();
        BeanUtils.copyProperties(menu,sysMenu);
        menu.setCreateTime(new Date());
        menu.setModifyTime(new Date());
        menu.setMenuId(idWorker.nextId());
        this.save(sysMenu);
        return ResponseVo.ok("新增成功");
    }

    @Override
    public ResponseVo updateMenu(SysMenuDto menu) {
        SysMenu sysMenu=new SysMenu();
        BeanUtils.copyProperties(menu,sysMenu);
        menu.setModifyTime(new Date());
        this.updateNotNull(sysMenu);
        return ResponseVo.ok("修改成功");
    }

    @Override
    public ResponseVo deleteMenu(Long id) {
        this.delete(id);
        roleMenuService.deleteByMenuId(id);
        sysMenuMapper.changeMenuToTop(id);
        return ResponseVo.ok("删除成功");
    }

    @Override
    public Map<String, Map<String, Object>> getUserMenu(Long userId) {
        List<SysMenu> userMenus = sysMenuMapper.findUserMenus(userId);
        Map<String,Map<String, Object>> result = new HashMap<>();
        Map<String,Object> menuMap= new HashMap<>();
        Map<String,Object> buttonMap = new HashMap<>();
        userMenus.forEach(menu -> {
            if (menu.getType().equals("0")){
                menuMap.put(menu.getPerms(),true);
            }else {
                buttonMap.put(menu.getPerms(),true);
            }
        });
        result.put("menu",menuMap);
        result.put("button",buttonMap);
        return result;
    }

    @Override
    public List<SysMenuDto> selectTotal() {
       // return null;
        List<SysMenu> sysMenus = this.selectAll();
        return BeanUtils.copyList(sysMenus,SysMenuDto.class);
    }

}
